import { CSSProperties, memo, useCallback, useMemo, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import {
  Avatar,
  Button,
  CheckboxOptionType,
  Form,
  Image,
  Input,
  message,
  Popconfirm,
  Radio,
  Switch,
  Table,
  Tag,
} from 'antd';
import { ColumnsType } from 'antd/es/table';
import {
  resAddUserAdmin,
  resChangeUserInfoAdmin,
  resLockUserAdmin,
  resUserListAdmin,
} from '@/services/user';
import { useAntdTable, useRequest } from 'ahooks';
import { isString, pick } from 'lodash';
import {
  labelCol,
  validateMessage,
  wrapperCol,
} from '@/components/AddressFormModal';
import EditModal from '@/components/EditModal';
import { orderNoStyle, style } from '@/pages/Profile/components/MyOrders';
import { formatTime, formatUrl } from '@/utils/format';

const createColumns = (
  refresh: () => void,
  showModal: (value: API.Userinfo) => void
): ColumnsType<API.Userinfo> => [
  {
    title: <div className={' font-bold'}>头像</div>,
    dataIndex: 'avatar',
    align: 'center',
    render: (avatar) =>
      avatar && isString(avatar) && <Avatar src={formatUrl(avatar)} alt="" />,
  },
  {
    title: <div className={' font-bold'}>账户名</div>,
    dataIndex: 'username',
    align: 'center',
    render: (username, user) => (
      <Link to={`/user_page/` + user.id}>{username}</Link>
    ),
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>昵称</div>,
    dataIndex: 'name',
    align: 'center',
    render: (name, user) => <Link to={`/user_page/` + user.id}>{name}</Link>,
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>邮箱</div>,
    dataIndex: 'email',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>手机号</div>,
    dataIndex: 'phone',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>签名</div>,
    dataIndex: 'sign',
    align: 'center',
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>创建时间</div>,
    dataIndex: 'created_at',
    align: 'center',
    render: (created_at) => formatTime(created_at),
    ellipsis: true,
  },
  {
    title: <div className={' font-bold'}>是否禁用</div>,
    dataIndex: 'is_locked',
    align: 'center',
    ellipsis: true,
    render: (is_locked, user) => (
      <Switch
        checked={Boolean(is_locked)}
        onChange={() => {
          resLockUserAdmin(user.id).then(() => {
            refresh();
          });
        }}
      />
    ),
  },
  {
    title: <div className={'font-bold'}>操作</div>,
    key: 'operate',
    ellipsis: true,
    render: (_, user) => (
      <Button
        type={'link'}
        onClick={() => {
          showModal(user);
        }}
      >
        编辑
      </Button>
    ),
  },
];

const UserManage: FC<PropsWithChildren<{}>> = () => {
  const [form] = Form.useForm();
  const { tableProps, pagination, search } = useAntdTable(
    (
      { pageSize, current },
      formData: Omit<API.UserListAdminParams, 'pageSize' | 'current'>
    ) => {
      return resUserListAdmin({
        pageSize,
        current,
        ...formData,
      });
    },
    { form, cacheKey: 'useUserAdminCache' }
  );

  const refresh = () => {
    pagination.changeCurrent(pagination.current);
  };

  const { submit, reset } = search;

  const searchForm = (
    <div className={''}>
      <Form form={form} className={'flex'}>
        <Form.Item name="name">
          <Input.Search placeholder="请输入用户名" onSearch={submit} />
        </Form.Item>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <Form.Item name="phone">
          <Input.Search placeholder="请输入手机号" onSearch={submit} />
        </Form.Item>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <Form.Item name="email">
          <Input.Search placeholder="请输入邮箱" onSearch={submit} />
        </Form.Item>
        <div className={'px-5'}>
          <Button
            htmlType={'reset'}
            onClick={() => {
              reset();
            }}
          >
            重置
          </Button>
        </div>
        <div className={'ml-auto'}>
          <Button
            onClick={() => {
              showModal();
            }}
            type={'primary'}
          >
            新增
          </Button>
        </div>
      </Form>
    </div>
  );

  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = useCallback(() => {
    setIsModalOpen(true);
  }, []);
  const handleCancel = useCallback(() => setIsModalOpen(false), []);

  const onFinish = useCallback((value: any) => {
    resAddUserAdmin(value).then(() => {
      message.success('添加用户成功');
      handleCancel();
      refresh();
    });
  }, []);

  const addModal = (
    <EditModal
      title={'添加用户'}
      isModalOpen={isModalOpen}
      onCancel={handleCancel}
      width={500}
    >
      <Form
        validateMessages={validateMessage}
        labelCol={labelCol}
        wrapperCol={wrapperCol}
        onFinish={onFinish}
      >
        <Form.Item label="创建方式" name="way" rules={[{ required: true }]}>
          <Radio.Group>
            <Radio value="phone">手机号</Radio>
            <Radio value="email">邮箱</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="账户名" name="account" rules={[{ required: true }]}>
          <Input placeholder={'邮箱/手机号'} />
        </Form.Item>
        <Form.Item label="密码" name="password" rules={[{ required: true }]}>
          <Input.Password placeholder={'8-16位，包含字母、数字'} />
        </Form.Item>
        <div>
          <Button htmlType={'submit'} block type={'primary'}>
            提交
          </Button>
        </div>
      </Form>
    </EditModal>
  );

  const [editForm] = Form.useForm<API.ChangeUserInfoAdminParams>();
  const [editOpen, setEditOpen] = useState<{
    show: boolean;
    editValue: API.Userinfo;
  }>({ show: false, editValue: {} as API.Userinfo });
  const showEditModal = useCallback((value: API.Userinfo) => {
    setEditOpen({ show: true, editValue: value });
    editForm.setFieldsValue(pick(value, ['name', 'email', 'phone', 'sign']));
  }, []);
  const handleEditCancel = useCallback(
    () => setEditOpen({ ...editOpen, show: false }),
    []
  );

  const columns = createColumns(refresh, showEditModal);

  const onEditFinish = useCallback(
    (value: API.ChangeUserInfoAdminParams) => {
      editOpen.editValue.id &&
        resChangeUserInfoAdmin(editOpen.editValue.id, value).then(() => {
          message.success('编辑用户成功');
          handleEditCancel();
          refresh();
        });
    },
    [editOpen, refresh, handleEditCancel]
  );

  const editUserModal = (
    <EditModal
      title={'编辑用户'}
      isModalOpen={editOpen.show}
      onCancel={handleEditCancel}
      width={500}
    >
      <Form
        form={editForm}
        validateMessages={validateMessage}
        labelCol={labelCol}
        wrapperCol={wrapperCol}
        onFinish={onEditFinish}
      >
        <Form.Item label="昵称" name="name">
          <Input />
        </Form.Item>
        <Form.Item label="手机号" name="phone">
          <Input />
        </Form.Item>
        <Form.Item label="邮箱" name="email">
          <Input />
        </Form.Item>
        <Form.Item label="签名" name="sign">
          <Input.TextArea />
        </Form.Item>
        <div>
          <Button htmlType={'submit'} block type={'primary'}>
            提交
          </Button>
        </div>
      </Form>
    </EditModal>
  );

  return (
    <div style={style} className={'p-4 hidden-scrollbar'}>
      {searchForm}
      <div className={'rounded-lg overflow-hidden'}>
        <Table columns={columns} rowKey="id" {...tableProps} />
      </div>
      {addModal}
      {editUserModal}
    </div>
  );
};

export default memo(UserManage);
